package com.wgke.kmmapp.android

import android.app.Application
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import com.wgke.kmmapp.Greeting
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.platform.ComposeView
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.russhwolf.settings.AndroidSettings
import com.wgke.kmmapp.AndroidHttpClient
import com.wgke.kmmapp.android.layout.page.mainPage
import com.wgke.kmmapp.bean.Version
import com.wgke.kmmapp.net.NetError
import com.wgke.kmmapp.net.NetLoader
import kotlinx.coroutines.*
import kotlinx.serialization.KSerializer
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.koin.core.context.startKoin
import org.koin.core.logger.Level
import org.koin.dsl.module

fun greet(): String {
    return Greeting().greeting()
}

class MainActivity : AppCompatActivity(), CoroutineScope by CoroutineScope(Dispatchers.Main) {

    val vm: MainVM by viewModel()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(ComposeView(this).apply { setContent { mainPage(vm) } })
        vm.loadData()
    }

}

class MainVM(override var net: NetLoader) : BaseViewModel(net) {
    val text = MutableLiveData<String>()
    var myText = mutableStateOf("等待获取接口数据")

    fun loadData() {

        val url = "http://mgr-api-test.jronline.com/baseservice-api/app/version/getVersionInfo"
        val params = mapOf("client-type" to "Android", "app-code" to "zsjr", "version" to "1.2.9")
        postLoading(NetModel(url, Version.serializer(), params),
            onFinish = {
                Log.e("NetModel", it.toString())
                text.postValue(it.toString())
                myText.value = it.toString()
            })
//        viewModelScope.launch(Dispatchers.Main) {
//            try {
//                val result = withContext(Dispatchers.IO) {
//
//                    net.post(url, params, Version.serializer())
//                }
//                text.postValue(result?.toString())
//                Log.e("viewModelScope", "" + result.toString())
//            } catch (e: Exception) {
//                Log.e("viewModelScope", e.message ?: "xxxxxxxxx")
//                if (e is NetError) {
//                    Log.e("viewModelScope-NetError", e.message ?: "xxxxxxxxx")
//                }
//            }
//        }
    }

    fun click() {
        myText.value = myText.value + "接收到点击事件"
    }
}

/**基础的view*/
abstract class BaseViewModel(open var net: NetLoader) : ViewModel() {
    val pageTitle = MutableLiveData<String>()
    val isLoading = MutableLiveData(false)
}

data class NetModel<T>(val url: String, val ks: KSerializer<T>, val param: Any?, val isNeed: Boolean = true)

/**简单封装*/
fun <T> BaseViewModel.postLoading(param: NetModel<T>, onFinish: (T) -> Unit, onError: ((Int, String) -> Unit?)? = null): Job {
    return viewModelScope.launch(Dispatchers.Main) {
        if (param.isNeed) isLoading.postValue(true)
        try {
            onFinish.invoke(withContext(Dispatchers.IO) { net.post(param.url, param.param, param.ks) } ?: "" as T)
            if (param.isNeed) isLoading.postValue(false)
        } catch (e: Exception) {
            if (param.isNeed) isLoading.postValue(false)
            if (e is NetError) onError?.invoke(e.code, e.msg ?: "") else onError?.invoke(-1, "网络出错，请稍后再试")
        }
    }
}


class App : Application() {
    override fun onCreate() {
        super.onCreate()
        initKoin()
    }

    private fun initKoin() {
        startKoin {
            if (BuildConfig.DEBUG) androidLogger(Level.ERROR)
            androidContext(this@App)
            modules(appModule)
        }
    }

    private val appModule = module {
        single { NetLoader(AndroidHttpClient(true)) }//APP整个生命周期，全局单例 val net: NetLoader by inject()
        single { }
        viewModel { MainVM(get()) }//APP整个生命周期，全局单例 val vm: MainVM by viewModel()
    }
}
